// 工具函数库
class Utils {
    // 计算两点之间的距离
    static distance(x1, y1, x2, y2) {
        return Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
    }

    // 计算两点之间的角度
    static angle(x1, y1, x2, y2) {
        return Math.atan2(y2 - y1, x2 - x1);
    }

    // 从角度和距离计算目标位置
    static getPositionFromAngle(x, y, angle, distance) {
        return {
            x: x + Math.cos(angle) * distance,
            y: y + Math.sin(angle) * distance
        };
    }

    // 限制数值在指定范围内
    static clamp(value, min, max) {
        return Math.min(Math.max(value, min), max);
    }

    // 线性插值
    static lerp(start, end, factor) {
        return start + (end - start) * factor;
    }

    // 生成随机整数
    static randomInt(min, max) {
        return Math.floor(Math.random() * (max - min + 1)) + min;
    }

    // 生成随机浮点数
    static randomFloat(min, max) {
        return Math.random() * (max - min) + min;
    }

    // 检查两个圆形是否碰撞
    static circleCollision(x1, y1, r1, x2, y2, r2) {
        const distance = this.distance(x1, y1, x2, y2);
        return distance < r1 + r2;
    }

    // 检查点是否在矩形内
    static pointInRect(x, y, rectX, rectY, rectWidth, rectHeight) {
        return x >= rectX && x <= rectX + rectWidth &&
               y >= rectY && y <= rectY + rectHeight;
    }

    // 检查两个矩形是否碰撞
    static rectCollision(x1, y1, w1, h1, x2, y2, w2, h2) {
        return x1 < x2 + w2 && x1 + w1 > x2 &&
               y1 < y2 + h2 && y1 + h1 > y2;
    }

    // 格式化时间（秒转换为分:秒）
    static formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = Math.floor(seconds % 60);
        return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
    }

    // 深拷贝对象
    static deepClone(obj) {
        if (obj === null || typeof obj !== 'object') return obj;
        if (obj instanceof Date) return new Date(obj.getTime());
        if (obj instanceof Array) return obj.map(item => this.deepClone(item));
        if (typeof obj === 'object') {
            const clonedObj = {};
            for (const key in obj) {
                if (obj.hasOwnProperty(key)) {
                    clonedObj[key] = this.deepClone(obj[key]);
                }
            }
            return clonedObj;
        }
    }

    // 生成UUID
    static generateUUID() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
            const r = Math.random() * 16 | 0;
            const v = c == 'x' ? r : (r & 0x3 | 0x8);
            return v.toString(16);
        });
    }

    // 数组洗牌
    static shuffleArray(array) {
        const shuffled = [...array];
        for (let i = shuffled.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }
        return shuffled;
    }

    // 获取数组中的随机元素
    static randomElement(array) {
        return array[Math.floor(Math.random() * array.length)];
    }

    // 检查对象是否为空
    static isEmpty(obj) {
        if (obj == null) return true;
        if (Array.isArray(obj) || typeof obj === 'string') return obj.length === 0;
        return Object.keys(obj).length === 0;
    }

    // 防抖函数
    static debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }

    // 节流函数
    static throttle(func, limit) {
        let inThrottle;
        return function() {
            const args = arguments;
            const context = this;
            if (!inThrottle) {
                func.apply(context, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    }

    // 颜色工具
    static hexToRgb(hex) {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    }

    static rgbToHex(r, g, b) {
        return "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
    }

    // 角度转换
    static degreesToRadians(degrees) {
        return degrees * (Math.PI / 180);
    }

    static radiansToDegrees(radians) {
        return radians * (180 / Math.PI);
    }

    // 向量操作
    static normalizeVector(x, y) {
        const length = Math.sqrt(x * x + y * y);
        if (length === 0) return { x: 0, y: 0 };
        return { x: x / length, y: y / length };
    }

    static dotProduct(x1, y1, x2, y2) {
        return x1 * x2 + y1 * y2;
    }

    // 贝塞尔曲线
    static bezierCurve(p0, p1, p2, p3, t) {
        const x = Math.pow(1 - t, 3) * p0.x + 3 * Math.pow(1 - t, 2) * t * p1.x + 
                  3 * (1 - t) * Math.pow(t, 2) * p2.x + Math.pow(t, 3) * p3.x;
        const y = Math.pow(1 - t, 3) * p0.y + 3 * Math.pow(1 - t, 2) * t * p1.y + 
                  3 * (1 - t) * Math.pow(t, 2) * p2.y + Math.pow(t, 3) * p3.y;
        return { x, y };
    }

    // 线段与圆的碰撞检测
    static lineCircleCollision(x1, y1, x2, y2, cx, cy, radius) {
        // 计算线段向量
        const lineX = x2 - x1;
        const lineY = y2 - y1;
        
        // 计算线段长度的平方
        const lineLengthSquared = lineX * lineX + lineY * lineY;
        
        // 如果线段长度为0，则退化为点与圆的碰撞检测
        if (lineLengthSquared === 0) {
            const dx = cx - x1;
            const dy = cy - y1;
            return dx * dx + dy * dy <= radius * radius;
        }
        
        // 计算最近点的参数t (0 <= t <= 1)
        const t = Math.max(0, Math.min(1, ((cx - x1) * lineX + (cy - y1) * lineY) / lineLengthSquared));
        
        // 计算线段上离圆心最近的点
        const closestX = x1 + t * lineX;
        const closestY = y1 + t * lineY;
        
        // 计算最近点到圆心的距离
        const distanceSquared = (cx - closestX) * (cx - closestX) + (cy - closestY) * (cy - closestY);
        
        // 判断是否碰撞
        return distanceSquared <= radius * radius;
    }
};

// 全局常量
const GAME_CONFIG = {
    CANVAS_WIDTH: 800,
    CANVAS_HEIGHT: 600,
    WORLD_WIDTH: 3000,  // 世界宽度
    WORLD_HEIGHT: 3000, // 世界高度
    FPS: 60,
    PLAYER_SPEED: 3,
    PLAYER_SIZE: 20,
    ENEMY_SIZE: 15,
    WEAPON_SIZE: 8,
    EXPERIENCE_ORB_SIZE: 10,
    MAX_ENEMIES: 50,
    ENEMY_SPAWN_RATE: 0.5,
    WEAPON_COOLDOWN: 500
    // 移除 EXPERIENCE_PER_LEVEL 和 UPGRADE_SELECTION_TIME，因为它们现在在 BALANCE_CONFIG 中定义
};

// 游戏状态枚举
const GAME_STATES = {
    MENU: 'menu',
    PLAYING: 'playing',
    UPGRADING: 'upgrading',
    GAME_OVER: 'game_over'
};

// 武器类型枚举
const WEAPON_TYPES = {
    KNIFE: 'knife',
    FIREBALL: 'fireball',
    LIGHTNING: 'lightning',
    ICE_SHARD: 'ice_shard',
    LASER: 'laser',
    ORBITAL: 'orbital',
    CLONE: 'clone',
    SHIELD: 'shield'
};

// 敌人类型枚举
const ENEMY_TYPES = {
    ZOMBIE: 'zombie',
    SKELETON: 'skeleton',
    GHOST: 'ghost',
    BOSS: 'boss'
}; 